package com.talent.web.service.impl;

import com.talent.web.config.security.JwtProvider;
import com.talent.web.config.security.TalentUserDetails;
import com.talent.web.config.security.phone.SmsCodeAuthenticationToken;
import com.talent.web.enums.ResponseEnum;
import com.talent.web.exception.TalentException;
import com.talent.web.feign.WxFeignClient;
import com.talent.web.feign.wx.WxLoginDto;
import com.talent.web.feign.wx.WxOpenIdResultVo;
import com.talent.web.feign.wx.WxPhoneResultVo;
import com.talent.web.model.dto.LoginDto;
import com.talent.web.model.dto.MobileLoginDto;
import com.talent.web.model.entity.TlUser;
import com.talent.web.service.ILoginService;
import com.talent.web.service.ITlUserService;
import com.talent.web.utils.DecryptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName：ResponseEnum
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: 登录接口实现类
 */
@Service
public class LoginServiceImpl  implements ILoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private JwtProvider jwtProvider;

    @Autowired
    private DecryptionUtils decryptionUtils;

    @Autowired
    private WxFeignClient wxFeignClient;

    @Autowired
    private ITlUserService tlUserService;




    @Override
    public String login(LoginDto loginDto) throws Exception {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //认证成功返回结果，应注意authentication对象放入安全上下文供后续的过滤器取用
        SecurityContextHolder.getContext().setAuthentication(authentication);
        TalentUserDetails userDetails = (TalentUserDetails)authentication.getPrincipal();
        return jwtProvider.generateToken(userDetails);
    }

    @Override
    public String loginByPhone(MobileLoginDto loginDto) {
        String mobile = loginDto.getMobile();
        String code = loginDto.getCode();
        SmsCodeAuthenticationToken authenticationToken = new SmsCodeAuthenticationToken(mobile,code);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //认证成功返回结果，应注意authentication对象放入安全上下文供后续的过滤器取用
        SecurityContextHolder.getContext().setAuthentication(authentication);
        TalentUserDetails userDetails = (TalentUserDetails)authentication.getPrincipal();
        return jwtProvider.generateToken(userDetails);
    }

    @Override
    public String wxLogin(WxLoginDto loginDto) {

        //1， 根据code掉微信获取openId
        WxOpenIdResultVo wxOpenIdResultVo = wxFeignClient.getOpenId("", "", loginDto.getCode(), null);

        String openid = wxOpenIdResultVo.getOpenid();
        TlUser tlUser = tlUserService.findUserByOpenId(openid);
        // 判断openId是否为空
        // openId为空 新增user对象 构建数据openId
        if(null == tlUser){
            tlUser = new TlUser();
            tlUser.setOpenId(openid);
        }
        // openId不为空 根据调用微信api后去手机号
        WxPhoneResultVo userPhone = wxFeignClient.getUserPhone("", openid, loginDto.getPhoneCode());
        //保存或修改客户
        tlUser.setPhone(userPhone.getPhone_info().getPhoneNumber());
        tlUserService.save(tlUser);
        //生成token
        return jwtProvider.generateToken(tlUser);
    }

    @Override
    public String appLoginByPhone(MobileLoginDto loginDto) {
        TlUser tlUser = tlUserService.selectUserByPhone(loginDto.getMobile());
        return jwtProvider.generateToken(tlUser);
    }

    @Override
    public void logout() {
        TalentUserDetails principal =(TalentUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String key = "user:"+principal.getId();
        redisTemplate.delete(key);
        SecurityContextHolder.clearContext();

    }

    @Override
    public void sendSms(String phone) {
        String code ="123";
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

        Object o = valueOperations.get(phone);
        if(o!=null){
            throw new TalentException(ResponseEnum.CAPTCHA_EXIT);
        }
        valueOperations.set(phone,code, 600,TimeUnit.SECONDS);
    }



}
